package com.zoc.web.prd;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.castor.Castor;
import org.nutz.castor.castor.String2Number;
import org.nutz.lang.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jmrztht.Global;
import com.jmrztht.MD5;
import com.zoc.common.SuperUtils;
import com.zoc.common.poi.ImportExcel;
import com.zoc.common.poi.UploadParam;
import com.zoc.entity.prd.LevelMaster;
import com.zoc.entity.prd.Member;
import com.zoc.entity.prd.PayDetail;
import com.zoc.entity.security.Branch;
import com.zoc.entity.security.Permission;
import com.zoc.entity.security.User;
import com.zoc.service.prd.LevelMasterService;
import com.zoc.service.prd.MemberService;
import com.zoc.web.security.BranchController;

@Controller
@RequestMapping(value = "member")
public class MemberController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private LevelMasterService levelMasterService;

	private static Logger logger = LoggerFactory.getLogger(MemberController.class);

	public Member getMember() {
		User user = SuperUtils.getSubjectUser();
		return memberService.fetch(user.getUsername());
	}

	@RequestMapping(value = "/main", method = RequestMethod.GET)
	public String main(Model model) {
		model.addAttribute("member", getMember());
		return "/security/main";
	}

	@RequestMapping(value = "/manager", method = { RequestMethod.GET, RequestMethod.POST })
	public String manager(Model model) {
		return "/prd/memberManager";
	}
	
	@RequestMapping(value="/batchSave",method ={RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String batchSave(MultipartHttpServletRequest request){
		try {
			ImportExcel<Member> in = new ImportExcel<Member>(Member.class);

			Iterator<String> it = request.getFileNames();

			UploadParam uploadParam = new UploadParam();
			
			uploadParam.setTemplate_path("templates/in/");
			
			uploadParam.setSheet_name("会员资料");
			
			uploadParam.setRow_start(2);
			
			uploadParam.setRow_end(1000);
			
			uploadParam.setCol_start(1);
			
			uploadParam.setCol_end(13);
			

			List<Member> lists = new ArrayList<Member>();
			

		
			while (it.hasNext()) {
				List<MultipartFile> files = request.getFiles(it.next());
				for (MultipartFile file : files) {

					// 传入数据
					lists.addAll(in.importExcel(file.getInputStream(), uploadParam));
				}
			}
			memberService.batchSave(lists);
			return "数据导入成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "数据导入失败";
		}
	}

	@RequestMapping(value = "/managerList", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	List<Member> managerList() {
		User user = SuperUtils.getSubjectUser();
		Member m = new Member();
		if("C".equals(user.getUser_type())){
			m.setChannel_id(user.getUsername());
		}
		
		return memberService.list(m);
	}

	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String admin(Model model) {
		return "/prd/admin";
	}

	@RequestMapping(value = "/enrich", method = { RequestMethod.GET })
	public String enrich(Model model) {
		model.addAttribute("member", getMember());
		return "/prd/enrich";
	}

	@RequestMapping(value = "/doEnrich", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	String save(@RequestParam("data") String data) {
		logger.debug(data);
		Member member = SuperUtils.parseObject(data, Member.class);
		memberService.save(member);
		return "保存成功";

	}

	@RequestMapping(value = "/level", method = { RequestMethod.GET, RequestMethod.POST })
	public String level(Model model) {
		String v_mid = Global.RB.getString("onlinepay.mid");
		Date currTime = new Date();
		SimpleDateFormat sf = new SimpleDateFormat((new StringBuilder("yyyyMMdd-")).append(v_mid).append("-hhmmss")
				.toString(), Locale.US);
		String v_oid = sf.format(currTime);
		model.addAttribute("v_oid", v_oid);

		LevelMaster lm = new LevelMaster();
		lm.setLevel_id("0");
		model.addAttribute("levelMaster", levelMasterService.list(lm).get(0));
		return "/prd/level";
	}

	@RequestMapping(value = "/payment", method = { RequestMethod.GET })
	public String payment(Model model) {
		model.addAttribute("member", getMember());
		return "/prd/payment";
	}

	@RequestMapping(value = "/send", method = { RequestMethod.GET, RequestMethod.POST })
	public String chinabank(Model model, @RequestParam("v_oid") String v_oid, @RequestParam("amount") String amount) {
		String cardno = "cardno";// request.getParameter("cardno");
		String v_mid = Global.RB.getString("onlinepay.mid");
		String v_key = Global.RB.getString("onlinepay.key");
		String v_amount = amount;// request.getParameter("amount");
		String v_moneytype = "CNY";
		String q_url = Global.RB.getString("onlinepay.queryurl");
		String v_url = Global.RB.getString("onlinepay.returnurl");
		String text = (new StringBuilder(String.valueOf(v_amount))).append(v_moneytype).append(v_oid).append(v_mid)
				.append(v_url).append(v_key).toString();
		MD5 md5 = new MD5();
		String v_md5info = md5.getMD5ofStr(text).toUpperCase();
		model.addAttribute("cardno", cardno);
		model.addAttribute("v_md5info", v_md5info);
		model.addAttribute("v_mid", v_mid);
		model.addAttribute("v_oid", v_oid);
		model.addAttribute("v_amount", v_amount);
		model.addAttribute("v_moneytype", v_moneytype);
		model.addAttribute("q_url", q_url);
		model.addAttribute("v_url", v_url);
		String datatime = getDate();
		model.addAttribute("remark1", datatime);
		model.addAttribute("remark2", (new StringBuilder(String.valueOf(v_oid))).append("_remark").toString());
		memberService.insertPayDetail(new PayDetail(v_oid, SuperUtils.getSubjectUser().getUsername(), new Date(),
				v_amount, "E"));
		return "/prd/send";
	}

	@RequestMapping(value = "/receive", method = { RequestMethod.GET, RequestMethod.POST })
	public String receive(HttpServletRequest request) {
		String key = Global.RB.getString("onlinepay.key");
		String v_oid = request.getParameter("v_oid");
		String v_pmode = request.getParameter("v_pmode");
		String v_pstatus = request.getParameter("v_pstatus");
		String v_pstring = request.getParameter("v_pstring");
		String v_amount = request.getParameter("v_amount");
		String v_moneytype = request.getParameter("v_moneytype");
		String v_md5str = request.getParameter("v_md5str");
		String remark1 = request.getParameter("remark1");
		String remark2 = request.getParameter("remark2");
		String text = (new StringBuilder(String.valueOf(v_oid))).append(v_pstatus).append(v_amount).append(v_moneytype)
				.append(key).toString();
		MD5 md5 = new MD5();
		String v_md5 = md5.getMD5ofStr(text).toUpperCase();
		if (v_md5str.equals(v_md5)) {
			String result = "";
			if ("30".equals(v_pstatus)) {
				request.setAttribute("paymentStatus", "支付失败！");
				result = "2";
			} else if ("20".equals(v_pstatus)) {
				request.setAttribute("paymentStatus", "支付成功！");
				result = "1";
				memberService.updatePayDetail(new PayDetail(v_oid, null, null, null, "S"));
			}
			/*
			 * M9019 m9019 = new M9019(); m9019.setOrderId(v_oid);
			 * m9019.setTxnStat(result); try { m9019.execute(); } catch
			 * (Exception e) { logger.error("执行M9019错误", e); }
			 */} else {
			request.setAttribute("paymentStatus", "支付信息不正确，可能被篡改。");
		}
		request.setAttribute("paymentOrderID", v_oid);
		request.setAttribute("paymentAmount", v_amount);
		request.setAttribute("paymentDate", remark1);

		return "/prd/receive";
	}

	@RequestMapping(value = "/paylist", method = { RequestMethod.GET, RequestMethod.POST })
	public String paylist(Model model, @RequestParam("v_oid") String v_oid) {
		List<PayDetail> payDetails = memberService.listPayDetail(new PayDetail(v_oid, null, null, null, null));
		PayDetail p = payDetails.get(0);
		if ("S".equals(p.getPay_status())) {
			Member member = new Member();
			member.setMember_id(p.getMember_id());
			member.setLevel("0");
			memberService.updateLevel(member);
		}
		model.addAttribute("p", p);
		return "/prd/paylist";
	}

	public static String getDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}

}
